/*
 * Copyright (c) 2022-2023 cetcclout Co., Ltd All rights reserved.
 * Sensor Adapter is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package com.cetccloud.cimp.adapter.handler.abstracts;

import cn.hutool.core.io.BufferUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.nio.Buffer;

/**
 * @author
 * @apiNote 对来自设备的数据做校验
 * @date 2022/10/14 14:35
 */
public abstract class AbstractCheckHandler extends DtuDataHandler {
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
    
    /**
     * 处理来自设备的数据
     */
    @Override
    public void fromDtu(Buffer buffer, Object context) {
        System.out.println("AbstractCheckHandler——fromDtu");
        boolean acceptable = this.validate(buffer, context, null);
        if (acceptable) {
            nextFromDtuHandler.fromDtu(buffer, context);
        }
    }

    /**
     * 处理来自设备查询返回信息
     */
    @Override
    public void fromDtuAT(Buffer buffer, Object context) {
        nextFromDtuHandler.fromDtuAT(buffer,context);
    }

    /**
     * 处理发往设备的数据
     */
    @Override
    public void toDtu(Buffer buffer, Object context) {
        System.out.println("AbstractCheckHandler——toDtu");
        try {
            JSONObject jsonObject = OBJECT_MAPPER.readValue((byte[]) buffer.array(), JSONObject.class).getJSONObject("content");
            boolean acceptable = this.validate(BufferUtil.createUtf8(JSONUtil.toJsonStr(jsonObject)),
                    "methods",(String)context, "inputData");
            if (acceptable) {
                nextToDtuHandler.toDtu(buffer, jsonObject.getStr("dtuId"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 报文语法检验
     * @param buffer
     * @return
     */
    public abstract boolean validate(Buffer buffer, Object context, String... paramPath);
}
